<?php
declare(strict_types=1);

namespace Modules\WeChat\Service;

use Cache;
use HiCommon\Repository\AdminsRepository;

class AccountService extends BaseService{

    /**
     * 绑定账号
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function binding($arr_input){
        $s_username = str_trim($arr_input['username']);
        $s_password = str_trim($arr_input['password']);
        $s_openid = str_trim($arr_input['openid']);
        if(strlen($s_username) <= 0){
            return hello_error('请输入手机号或账号');
        }
        if(strlen($s_password) <= 0){
            return hello_error('请输入密码');
        }
        if(strlen($s_openid) <= 0){
            return hello_error('请重新获取openid');
        }

        $arr_where = [
          'username'=>$s_username,
          'phone'=>$s_username,
        ];

        //验证账户
        $res = AdminsRepository::base_get_one_orwhere($arr_where);
        if(is_null($res)){
            return hello_error('用户不存在');
        }
        $arr_admin_user = $res->toarray();
        if($arr_admin_user['type'] != 2 && $arr_admin_user['type'] != 3){
            return hello_error('用户类型错误，只有检测站或者维修店才能绑定');
        }
        if($arr_admin_user['pass'] != $s_password){
            return hello_error('密码错误');
        }
        if($arr_admin_user['openid'] == $s_openid){
            return hello_error('您已绑定账号');
        }
        if(!empty($arr_admin_user['openid'])){
            return hello_error('账号已被绑定，请更换账号');
        }
        if($arr_admin_user['status'] == 2){
            return hello_error('用户已被禁用');
        }

        //绑定
        $arr_data = [
          'id'=>$arr_admin_user['id'],
          'openid'=>$s_openid,
        ];
        $res = AdminsRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('绑定失败');
        }
        return  hello_success('绑定成功');

    }

    /**
     * 解绑账号
     *
     * @param string $s_openid
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function unbinding($s_openid = ''){
        $s_openid = str_trim($s_openid);
        if(strlen($s_openid) <= 0){
            return hello_error('请重新获取openid');
        }

        //解绑
        $arr_where = ['openid'=>$s_openid];
        $arr_input = ['openid'=>''];
        $res = AdminsRepository::edit_by_where($arr_where, $arr_input);
        if(!$res){
            return hello_error('解绑失败');
        }

        $key  = 'wechat_'.$s_openid;
        Cache::pull($key);
        return  hello_success('解绑成功');

    }




}